package com.totcy.atom.model;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.totcy.atom.CommonValues;
import com.totcy.atom.bean.GankTypeBean;
import com.totcy.atom.bean.response.GankResponse;
import com.totcy.atom.net.HttpManager;
import com.totcy.atom.net.exception.ApiException;
import com.totcy.atom.net.subscriber.BaseHttpSubscriber;
import com.totcy.atom.presenter.contract.GankTypeListContract;
import com.totcy.baselibrary.base.mvpbase.BaseModelImpl;
import com.totcy.baselibrary.httpcache.ACache;

import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * description: gankio 分类数据 model
 * author: Totcy
 * date: 2017/11/2 14:49
 * update: 2017/11/3
 */

public class GankTypeListModel extends BaseModelImpl implements GankTypeListContract.Model {

    private BaseHttpSubscriber<List<GankTypeBean>> subscriber;
    private ACache aCache;
    private Gson gson = new Gson();


    public GankTypeListModel(Context context) {
        super(context);
        aCache = ACache.get(context);
    }

    @Override
    public void getGankTypeData(final String type, final int pageSize, final int curPage, final DataCallback callback) {

        //gank数据并不是这个项目的主要服务器，因此没有使用同一的封装

        HttpManager.getApiService(mContext)
                .getImageList(CommonValues.GANK_BASE_URL + type + "/" + pageSize + "/" + curPage)
                //使用map对结果进行转换
                .map(new Function<GankResponse<List<GankTypeBean>>, List<GankTypeBean>>() {
                    @Override
                    public List<GankTypeBean> apply(@NonNull GankResponse<List<GankTypeBean>> response) throws Exception {
                        if (!response.isError()) {
                            return response.getResults();
                        } else {
                            throw new ApiException(500, "Gank服务器异常");
                        }
                    }
                })
                //线程调度
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                //结果处理
                .subscribe(subscriber = new BaseHttpSubscriber<List<GankTypeBean>>() {
                    @Override
                    public void onSuccess(List<GankTypeBean> images) {
                        callback.onDataSuccess(images);
                        if (curPage == 1) {
                            aCache.put(CommonValues.GANK_BASE_URL + type + "/" + curPage, gson.toJson(images));
                        }
                    }

                    @Override
                    public void onError(int code, String errorMsg) {
                        if (code == ApiException.Code_UnConnected && curPage == 1) {
                            String json = aCache.getAsString(CommonValues.GANK_BASE_URL + type + "/" + curPage);
                            if (!TextUtils.isEmpty(json)) {
                                List<GankTypeBean> images = gson.fromJson(
                                        json,
                                        new TypeToken<List<GankTypeBean>>() {
                                        }.getType()
                                );
                                callback.onDataSuccess(images);
                            }

                        }
                        callback.onDataNotAvailable();
                    }
                });
    }

    @Override
    public void canCelRequest() {
        if (subscriber != null) {
            subscriber.unSubscribe();
        }
    }
}